﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using TeachingEval.Sys.Model;

namespace TeachingEval.Sys.DAL
{
    public class BaseDal<T>where T:class,new()
    {
        //TeachingEval_Sys_Entities Db = new TeachingEval_Sys_Entities();
        public DbContext Db
        {
            get { return DbContextFactory.GetCurrentDbContext(); }
        }

        #region 查询
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLamda)
        {
            return Db.Set<T>().Where(whereLamda).AsQueryable();
        }
        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total,
                                                Expression<Func<T, bool>> whereLamda,
                                                Expression<Func<T, S>> orderByLamda,
                                                bool isAsc
            )
        {
            total = Db.Set<T>().Where(whereLamda).Count();
            if (isAsc)
            {
                var temp = Db.Set<T>().Where(whereLamda)
                           .OrderBy<T, S>(orderByLamda)
                           .Skip(pageSize * (pageIndex - 1))
                           .Take(pageSize).AsQueryable();
                return temp;
            }
            else
            {
                var temp = Db.Set<T>().Where(whereLamda)
                           .OrderByDescending<T, S>(orderByLamda)
                           .Skip(pageSize * (pageIndex - 1))
                           .Take(pageSize).AsQueryable();
                return temp;
            }
        }
        #endregion

        #region cud

        public T Add(T entity)
        {
            Db.Set<T>().Add(entity);
            Db.SaveChanges();
            return entity;
        }

        public bool Update(T entity)
        {
            Db.Entry(entity).State = EntityState.Modified;
            return Db.SaveChanges() > 0;
        }

        public bool Delete(T entity)
        {
            Db.Entry(entity).State = EntityState.Deleted;
            return Db.SaveChanges() > 0;
        }

        #endregion
    }
}
